package it.mauriziobasile.andoid.aub.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;

public class CacheUtil {

    public static long JSONcacheExpireMillis = 1000 * 60 * 30;

    public static CacheObj getFromCache(Context context) {
        Logger.d("getFromCache");
        File cdir = context.getCacheDir();
        Logger.d("cache dir [" + cdir.getAbsolutePath() + "]");
        CacheObj co = null;
        if (!cdir.exists()) {
            try {
                Logger.d("cache dir creation");
                cdir.createNewFile();
            } catch (IOException e) {
                Logger.e("cache dir error [" + e.getMessage() + "]");
            }
        }
        File cfile = new File(cdir.getAbsolutePath(), "hosts.obj");
        Logger.d("cache file [" + cfile.getAbsolutePath() + "]");
        if (!cfile.exists()) {
            Logger.d("cache file creation does not exixst! returning..");
            return null;
        }
        try {
            FileInputStream fin = new FileInputStream(cfile);
            ObjectInputStream ois = new ObjectInputStream(fin);
            co = (CacheObj) ois.readObject();
            Logger.d("cache file read [" + cfile.length() + "] byte");
            ois.close();
        } catch (Exception e) {
            Logger.e("cache file reading error [" + e.getMessage() + "] so return");
            return null;
        }
        return co;
    }

    public static void setToCache(Context context, CacheObj obj) {
        Logger.d("setToCache");
        File cdir = context.getCacheDir();
        Logger.d("cache dir [" + cdir.getAbsolutePath() + "]");
        if (!cdir.exists()) {
            try {
                Logger.d("cache dir creation");
                cdir.createNewFile();
            } catch (IOException e) {
                Logger.e("cache dir error [" + e.getMessage() + "]");
            }
        }
        File cfile = new File(cdir.getAbsolutePath(), "hosts.obj");
        Logger.d("cache file [" + cfile.getAbsolutePath() + "]");
        if (!cfile.exists()) {
            try {
                Logger.d("cache file creation");
                cfile.createNewFile();
            } catch (IOException e) {
                Logger.e("cache file error [" + e.getMessage() + "]");
            }
        }
        try {
            FileOutputStream fout = new FileOutputStream(cfile);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(obj);
            oos.flush();
            Logger.d("cache file written [" + cfile.length() + "] bytes");
            oos.close();
        } catch (Exception e) {
            Logger.e("cache file writing error [" + e.getMessage() + "]");
        }
    }

}
